<template>
    <a-layout style="min-height: 100vh">
        <a-layout :style="{
            backgroundImage: 'url(' + backGroundImg + ')',
            backgroundRepeat: 'no-repeat', backgroundSize: '1600px 200px'
        }" style="background-color: #fff;">
            <a-layout-header style="background: transparent; padding: 0; margin-bottom: 20px;">
                <div style="display: flex;">
                    <div>
                        <img src="@/assets/logo-no-background.png" style="height: 60px;" @click="$router.push('/homepage_demo' + '?randomId=' + Math.random())" />
                    </div>
                    <div v-if="!login" style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-button style="background: transparent; color: white" @click="onLoginShow">
                            <template #icon><user-outlined style="color: white"/></template>
                            登录
                        </a-button>
                    </div>
                    <div v-else style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-dropdown>
                            <a-button style="background: transparent; color: white">
                                <user-outlined style="color: white"/>
                                {{ $store.state.username }}
                                <DownOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="onMenuClick">
                                    <a-menu-item key="center">
                                        <span style="display: flex; justify-content: center;">个人中心</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="favorite">
                                        <span style="display: flex; justify-content: center;">我的收藏</span>
                                    </a-menu-item>
                                    <a-menu-item key="interest">
                                        <span style="display: flex; justify-content: center;">我的关注</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="logout">
                                        <span style="display: flex; justify-content: center;">退出登录</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
                <hr class="custom-divider" />
            </a-layout-header>
            <a-layout-content>
                <div style="margin-top: 30px; margin-left: 420px">
                    <a-select defaultValue="title" :options="searchOptions" v-model:value="searchField" size="large" style="width: 80px" />
                    <a-input v-model:value="searchQuery" placeholder="请输入检索词" size="large" style="width: 580px; margin-left: 10px" />
                    <a-button type="primary" size="large" style="width: 100px; margin-left: 10px" @click="onSearch">
                        <template #icon><SearchOutlined /></template>
                        检索
                    </a-button>
                    <span style="color: white; margin-left: 10px ;cursor: pointer" @click="$router.push('/advancedSearch_demo')">高级检索></span>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: flex-start; width: 1200px; margin-left: 200px; margin-top: 80px;">
                    <div id="detail" v-if="data" style="width: 1000px; ">
                        <a-card style="border-width: 2px;">
                            <p :style="{ color: '#333333', fontSize: '20px', cursor: 'pointer'}">
                                {{data.title}}
                            </p>
                            <p style="color: #6C6C6C">
                                <!-- 作者列表，可跳转至作者界面 -->
                                作者:
                                <template v-for=" (author, index) in data.authors"
                                          :key="author.author_id">
                                    <u :style="{ color: author.isHovered ? '#6C6C6C' : '#0B0E47', textDecoration: author.isHovered ? 'underline' : 'none', cursor: 'pointer' }"
                                       @mouseover="author.isHovered = true"
                                       @mouseleave="author.isHovered = false"
                                       @click="handleAuthor(author.author_id)">
                                        {{ author.author_name }}
                                    </u>
                                    <span v-if="index < data.authors.length - 1">; </span>
                                </template>
                            </p>
                            <a-typography-paragraph
                                    :ellipsis="ellipsis ? { rows: 6, expandable: true, symbol: '展开∨' } : false"
                                    :content="data.paper_abstract"
                            />
                            <p style="color: #6C6C6C; line-height: 2">
                                所属学科:
                                <template v-for=" (cat, index) in data.categories">
                                        <span style="color: #0B0E47">{{ cat }}
                                        </span>
                                    <span v-if="index < data.categories.length - 1">; </span>
                                </template>
                                <br/>
                                <span v-if="data.doi">
                                        DOI: <span style="color: #0B0E47">{{data.doi}}</span>
                                        <br/>
                                    </span>
                                <span v-if="data.journal_ref">
                                        发表期刊: <span style="color: #0B0E47">{{ data.journal_ref }}</span>
                                        <br/>
                                    </span>
                                更新时间:
                                <span style="color: #0B0E47">{{data.update_date}}</span>
                            </p>
                            <a-button v-if="data.favorite" :size="large" style="background-color: #EFEFEF" @click="handleFavorite(data.paper_id)">
                                <template #icon>
                                    <star-filled :style="{color: '#FCCA00'}"/>
                                </template>
                                取消收藏
                            </a-button>
                            <a-button v-else :size="large" style="background-color: #EFEFEF" @click="handleFavorite(data.paper_id)">
                                <template #icon>
                                    <StarOutlined />
                                </template>
                                加入收藏
                            </a-button>
                            <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="handlePDF(data.url)">
                                <template #icon>
                                    <ReadOutlined />
                                </template>
                                在线阅读
                            </a-button>
                            <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="$router.push('/similar_paper?paper_id=' + data.paper_id)">
                                <template #icon>
                                    <PaperClipOutlined />
                                </template>
                                查看相似论文
                            </a-button>
                        </a-card>
                    </div>
                    <a-anchor>
                        <a-anchor-link href="#detail" title="基本信息" />
                        <a-anchor-link href="#ref_net" title="引文网络" />
                        <a-anchor-link href="#key_cloud" title="关键词云" />
                        <a-anchor-link href="#similar" title="相关文献推荐" />
                    </a-anchor>
                </div>
                <div id="ref_net" v-if="refList" style="margin-left: 200px; margin-top: 30px; width: 1000px; background-color: #F5F5FA">
                    <div style="margin: 20px">
                        <div class="tab-header">
                            引文网络
                        </div>
                        <hr class="custom-divider" />
                        <div style="display: flex; justify-content: center;">
                            <div ref="chart" style="width: 500px; height: 300px;"></div>
                        </div>
                        <a-tabs v-model:activeKey="activeKey">
                            <a-tab-pane key="1" tab="参考文献">
                                <span style="font-size: 12px">共 {{ refTotal }} 条文献</span>
                                <br/>
                                <span v-for=" (item, i) in paginatedRefList">
                                    [{{ (currentPageRef-1)*10+i+1}}]
                                    <span v-if="item.cite_id"
                                          :style="{ color: item.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: item.isTitleHovered ? 'underline' : 'none' , cursor: 'pointer'}"
                                          @mouseover="item.isTitleHovered = true"
                                          @mouseleave="item.isTitleHovered = false"
                                          @click="handleRead(item.cite_id)">
                                        <span v-if="item.title.endsWith('.')">{{ item.title }}</span>
                                        <span v-else>{{ item.title }}.</span>
                                    </span>
                                    <span v-else>
                                        <span v-if="item.title.endsWith('.')">{{ item.title }}</span>
                                        <span v-else>{{ item.title }}.</span>
                                    </span>
                                    <span v-if="item.authors">&nbsp;{{item.authors}}.</span>
                                    <span v-if="item.journal">&nbsp;{{item.journal}},</span>
                                    <span v-if="item.date">{{item.date}}</span>
                                    <br/>
                                </span>
                                <div style="margin-top: 10px; display: flex; justify-content: center;">
                                    <a-pagination size="small" v-model:current="currentPageRef" :total="refTotal" :showSizeChanger="false" @change="onPageRefChange" />
                                </div>
                            </a-tab-pane>
                            <a-tab-pane key="2" tab="引证文献">
                                <span style="font-size: 12px">共 {{ citeTotal }} 条文献</span>
                                <br/>
                                <span v-for=" (item, i) in paginatedCiteList">
                                    [{{ (currentPageCite-1)*10+i+1}}]
                                    <span v-if="item.cite_id"
                                          :style="{ color: item.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: item.isTitleHovered ? 'underline' : 'none' , cursor: 'pointer'}"
                                          @mouseover="item.isTitleHovered = true"
                                          @mouseleave="item.isTitleHovered = false"
                                          @click="handleRead(item.cite_id)">
                                        <span v-if="item.title.endsWith('.')">{{ item.title }}</span>
                                        <span v-else>{{ item.title }}.</span>
                                    </span>
                                    <span v-else>
                                        <span v-if="item.title.endsWith('.')">{{ item.title }}</span>
                                        <span v-else>{{ item.title }}.</span>
                                    </span>
                                    <span v-if="item.authors">&nbsp;{{item.authors}}.</span>
                                    <span v-if="item.journal">&nbsp;{{item.journal}},</span>
                                    <span v-if="item.date">{{item.date}}</span>
                                    <br/>
                                </span>
                                <div style="margin-top: 10px; display: flex; justify-content: center;">
                                    <a-pagination size="small" v-model:current="currentPageCite" :total="citeTotal" :showSizeChanger="false" @change="onPageCiteChange" />
                                </div>
                            </a-tab-pane>
                        </a-tabs>
                    </div>
                </div>
                <div id="key_cloud" style="margin-left: 200px; margin-top: 30px; width: 1000px; background-color: #F5F5FA">
                    <div style="margin: 20px">
                        <div class="tab-header">
                            关键词云
                        </div>
                        <hr class="custom-divider" />
                        <div style="display: flex; justify-content: center;">
                            <a-spin :spinning="loadingPK">
<!--                                <img src="@/assets/paperKeywords.png">-->
                                <img :src="loadingPK === true ? '' : require('@/assets/paperKeywords.png')">
                            </a-spin>
                        </div>
                    </div>
                </div>
                <div id="similar" style="margin-left: 200px; margin-top: 30px; width: 1000px; background-color: #F5F5FA">
                    <div style="margin: 20px">
                        <div class="tab-header">
                            相关推荐
                        </div>
                        <hr class="custom-divider" />
<!--                        <span style="font-size: 12px">共 {{ mock_Total }} 条文献</span>-->
<!--                        <br/>-->
                        <span v-for=" (item, i) in mock_paginatedList">
                                    [{{ (mock_currentPage-1)*10+i+1}}]
                                    <span v-if="item.cite_id"
                                          :style="{ color: item.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: item.isTitleHovered ? 'underline' : 'none' , cursor: 'pointer'}"
                                          @mouseover="item.isTitleHovered = true"
                                          @mouseleave="item.isTitleHovered = false"
                                          @click="handleRead(item.cite_id)">
                                        <span v-if="item.title.endsWith('.')">{{ item.title }}</span>
                                        <span v-else>{{ item.title }}.</span>
                                    </span>
                                    <span v-else>
                                        <span v-if="item.title.endsWith('.')">{{ item.title }}</span>
                                        <span v-else>{{ item.title }}.</span>
                                    </span>
                                    <span v-if="item.authors">&nbsp;{{item.authors}}.</span>
                                    <span v-if="item.journal">&nbsp;{{item.journal}},</span>
                                    <span v-if="item.date">{{item.date}}</span>
                                    <br/>
                                </span>
<!--                        <div style="margin-top: 10px; display: flex; justify-content: center;">-->
<!--                            <a-pagination size="small" v-model:current="mock_currentPage" :total="mock_Total" :showSizeChanger="false" @change="mock_onPageChange" />-->
<!--                        </div>-->
                    </div>
                </div>
                <a-modal v-model:visible="loginShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">欢迎登录</div>
                            <a-form
                                    :model="loginForm"
                                    name="normal_login"
                                    class="login-form"
                                    style="margin-top: 20px"
                                    @finish="onLoginFinish"
                            >
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请输入账号' }]"
                                >
                                    <a-input v-model:value="loginForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请输入密码' }]"
                                >
                                    <a-input-password v-model:value="loginForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-form-item name="remember" no-style>
                                        <a-checkbox v-model:checked="loginForm.remember">自动登录</a-checkbox>
                                    </a-form-item>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-button :disabled="disabled" type="primary" html-type="submit" class="login-form-button" style="width: 100%">
                                        登录
                                    </a-button>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
                                        <a @click="onRegisterShow">注册新用户</a>
                                        <a style="float: right;">忘记密码</a>
                                    </div>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
                <a-modal v-model:visible="registerShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">注册账号</div>
                            <a-form
                                    layout="horizontal"
                                    ref="formRef"
                                    :model="registerForm"
                                    style="margin-top: 20px"
                                    @finish="onRegisterFinish">
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请设置用户名' },{ message: '用户名已被占用', validator: validateUsername}]">
                                    <a-input v-model:value="registerForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请设置密码' }]">
                                    <a-input-password v-model:value="registerForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item
                                        label="身份"
                                        name="identity"
                                        :rules="[{ required: true, message: '请选择身份' }]">
                                    <a-select v-model:value="registerForm.identity" :options="identityOptions" placeholder="请选择身份"/>
                                </a-form-item>

                                <a-form-item
                                        label="邮箱"
                                        name="email">
                                    <a-input v-model:value="registerForm.email" placeholder="请绑定邮箱">
                                        <template #prefix>
                                            <mail-outlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item>
                                    <a-button :disabled="registerDisabled" type="primary" html-type="submit" style="width: 70%">
                                        注册
                                    </a-button>
                                    <a-button style="margin-left: 5%; width: 25%" @click="() => formRef.resetFields()">
                                        清空
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
            </a-layout-content>
            <a-layout-footer style="background: #000; text-align: center">
                <p style="color:#fff">©{{ new Date().getFullYear() }} {{ systemTitle }}</p>
                <p style="color:#fff">
                    <a @click.prevent="$router.push('/about')">关于</a>&nbsp;|&nbsp;
                    <a>开发团队</a>&nbsp;|&nbsp;
                    <a href="https://gitee.com/shenyang-theone/theone-recsys">了解更多</a>
                </p>
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, ref, toRefs} from "vue";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import globalVariable from "@/components/mathJax/globalVariable";
import {logout as logout_request} from "@/api/post/logout";
import {login} from "@/api/post/login";
import {user_info} from "@/api/post/user_info";
import {notification} from "ant-design-vue";
import {register} from "@/api/post/register";
import {validate_username} from "@/api/post/validate_username";
import {
    DownOutlined, PaperClipOutlined, ReadOutlined, StarFilled, StarOutlined,
    UserOutlined
} from "@ant-design/icons-vue";
import {paper_detail} from "@/api/post/paper_detail";
import {favorite} from "@/api/post/favorite";
import {search} from "@/api/post/search";
import {get_references} from "@/api/post/get_references";
import {get_citations} from "@/api/post/get_citations";
import {browsing} from "@/api/post/browsing";
import * as echarts from "echarts";
import {generate_paperKeywords} from "@/api/post/generate_paperKeywords";
import {mock_rec} from "@/api/post/mock_rec";

export default defineComponent({
    components: {
        StarOutlined,
        StarFilled,
        ReadOutlined,
        PaperClipOutlined,
        UserOutlined,
        DownOutlined,
    },
    setup() {
        // -------------onMounted钩子，组件挂载完毕异步加载数据--------------
        onMounted(() => {
            // 取参数
            state.paperId = parseInt($route.query.paper_id);
            state.login = !store.state.logout;
            state.searchField = $route.query.searchField || 'title';
            state.searchQuery = $route.query.searchQuery || '';
            state.tagsChecked = $route.query.tagsChecked ? JSON.parse($route.query.tagsChecked) : [];
            // 参数格式不正确
            if (isNaN(state.paperId)) {
                router.push('/homepage_demo')
            }
            // 调用搜索接口
            paper_detail(state.paperId).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.data = response.data.data.paper;
                    document.title = state.data.title + "-论文详情";
                    state.data.isTitleHovered = false;
                    state.data.authors.forEach((author) => {
                        // 区分author，为每个author设置单独的isHovered属性
                        author.isHovered = false;
                    });

                    // 根据url获取arxivId
                    const url = state.data.url;
                    // 使用最后一个斜杠后面的内容作为id
                    const lastIndex = url.lastIndexOf("/");
                    // 截取id值
                    const arxivId = url.substring(lastIndex + 1);

                    // 获取mock假数据
                    mock_rec(arxivId).then((response) => {
                        if (response.data.status.code === 0) {
                            state.mock_List = response.data.data;
                            state.mock_Total = response.data.data.length;

                            // 处理数据：用于设置悬停样式
                            state.mock_List.forEach((paper) => {
                                // 区分 Title，为每个 paper 设置单独的 isTitleHovered 属性
                                paper.isTitleHovered = false;
                            });
                        }
                    })

                    // 构建引文网络关系图
                    // 基于准备好的dom，初始化echarts实例
                    const myChart = echarts.init(chart.value);
                    // 显示加载中动画
                    myChart.showLoading();

                    const promise1 = get_references(arxivId);
                    const promise2 = get_citations(arxivId);
                    let refs = null;
                    let cites = null;

                    // 等待两个异步操作完成
                    Promise.all([promise1, promise2]).then((responses) => {
                        // 处理参考文献数据
                        const referencesResponse = responses[0];
                        if (referencesResponse.data.status.code === 0) {
                            refs = referencesResponse.data.data;
                            state.refList = referencesResponse.data.data;
                            state.refTotal = referencesResponse.data.data.length;

                            // 处理数据：用于设置悬停样式
                            state.refList.forEach((paper) => {
                                // 区分 Title，为每个 paper 设置单独的 isTitleHovered 属性
                                paper.isTitleHovered = false;
                            });
                        }

                        // 处理引证文献数据
                        const citationsResponse = responses[1];
                        if (citationsResponse.data.status.code === 0) {
                            cites = citationsResponse.data.data;
                            state.citeList = citationsResponse.data.data;
                            state.citeTotal = citationsResponse.data.data.length;

                            // 处理数据：用于设置悬停样式
                            state.citeList.forEach((paper) => {
                                // 区分 Title，为每个 paper 设置单独的 isTitleHovered 属性
                                paper.isTitleHovered = false;
                            });
                        }

                        // 两个异步操作完成后，构建引文网络关系图
                        // 这里可以放置构建 echarts 实例的代码
                        // 隐藏加载中动画
                        myChart.hideLoading();

                        // 处理中心论文作者字段
                        let centAuthors = "";
                        for (let i = 0; i < state.data.authors.length; i++) {
                            centAuthors += state.data.authors[i].author_name+";";
                        }
                        // 去掉最后一个分号
                        centAuthors = centAuthors.slice(0, -1);

                        // 添加中心论文节点
                        let centNode = {
                            // id必须是string类型!!!这里只要保证id不重复即可
                            "id": "-1",
                            "paper_id": state.data.paper_id,
                            "title":state.data.title,
                            "authors": centAuthors,
                            "journal": state.data.journal_ref,
                            "date": state.data.update_date,
                            // 节点大小
                            "symbolSize": 30,
                            // 表示中心论文
                            "category": 2
                        };
                        graph.nodes.push(centNode);

                        // 将获取到的参考文献数据转化为graph关系
                        for (let i = 0; i < refs.length; i++) {
                            // 声明当前遍历的文献
                            let ref = refs[i];

                            // 根据paper_id设置symbolSize，默认值为10，存在链接跳转设置为20
                            let symbolSize = 10;
                            if(ref.cite_id) symbolSize = 20;

                            // 添加参考文献节点
                            let refNode = {
                                // id必须是string类型!!!这里只要保证id不重复即可
                                "id": i.toString(),
                                "paper_id": ref.cite_id,
                                "title": ref.title,
                                "authors": ref.authors,
                                "journal": ref.journal,
                                "date": ref.date,
                                // 节点大小
                                "symbolSize": symbolSize,
                                // 表示参考文献
                                "category": 0,
                            };
                            graph.nodes.push(refNode);

                            let refLink = {
                                "source": i.toString(),
                                "target": "-1",
                                "relationship": "参考关系",
                                lineStyle: {
                                    curveness: 0.3
                                },
                            };
                            graph.links.push(refLink);
                        }

                        // 将获取到的引证文献数据转化为graph关系
                        for (let i = 0; i < cites.length; i++) {
                            // 声明当前遍历的文献
                            let cite = cites[i];

                            // 根据paper_id设置symbolSize，默认值为10，存在链接跳转设置为20
                            let symbolSize = 10;
                            if(ref.cite_id) symbolSize = 20;

                            // 添加引证文献节点
                            let citeNode = {
                                // id必须是string类型!!!这里只要保证id不重复即可
                                "id": (i+refs.length).toString(),
                                "paper_id": cite.cite_id,
                                "title": cite.title,
                                "authors": cite.authors,
                                "journal": cite.journal,
                                "date": cite.date,
                                // 节点大小
                                "symbolSize": symbolSize,
                                // 表示引证文献
                                "category": 1,
                            };
                            graph.nodes.push(citeNode);

                            let citeLink = {
                                "source": (i+refs.length).toString(),
                                "target": "-1",
                                "relationship": "引证关系",
                                lineStyle: {
                                    curveness: 0.3
                                },
                            };
                            graph.links.push(citeLink);
                        }

                        // 指定图表的配置项和数据
                        const option = {
                            tooltip: {
                                trigger: 'item',
                                formatter: function(params) {
                                    if (params.dataType === 'edge') { // 如果当前是边
                                        return '<'+params.data.relationship+'>';
                                    } else { // 如果是节点
                                        let tooltipContent = '<' + graph.categories[params.data.category].name + '信息>' +
                                                '<br/>题名:&emsp;&emsp;&nbsp;' + params.data.title;
                                        // 判断是否存在作者信息，如果存在则添加到提示框内容中
                                        if (params.data.authors) tooltipContent += '<br/>作者:&emsp;&emsp;&nbsp;'+params.data.authors;
                                        if(params.data.journal) tooltipContent += '<br/>发表期刊:&nbsp;'+params.data.journal+','+params.data.date;
                                        return tooltipContent;
                                    }
                                }
                            },
                            // 图例
                            legend: [
                                {
                                    data: graph.categories.map(function (a) {
                                        return a.name;
                                    })
                                }
                            ],
                            animationDuration: 1500,
                            animationEasingUpdate: 'quinticInOut',
                            series: [
                                {
                                    name: 'Cite_Net',
                                    type: 'graph',
                                    layout: 'circular',
                                    data: graph.nodes,
                                    links: graph.links,
                                    categories: graph.categories,
                                    // 开启平移和缩放
                                    roam: true,
                                    label: {
                                        position: 'right',
                                        formatter: '{b}'
                                    },
                                    // 自动隐藏重叠标签
                                    labelLayout: {
                                        hideOverlap: true
                                    },
                                    // scaleLimit: {
                                    //     min: 0.4,
                                    //     max: 2
                                    // },
                                    lineStyle: {
                                        color: 'source',
                                        // curveness: 0.3
                                    },
                                    emphasis: {
                                        // 强调节点
                                        focus: 'adjacency',
                                        // 突出显示边
                                        lineStyle: {
                                            width: 10
                                        }
                                    }
                                }
                            ]
                        };

                        // 使用刚指定的配置项和数据显示图表。
                        myChart.setOption(option);

                        // 添加点击事件监听器
                        myChart.on('click', function(params) {
                            if (params.dataType === 'node') {
                                // 如果点击的是节点，跳转至该论文信息界面
                                let paper_id = params.data.paper_id;
                                if(paper_id){
                                    window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
                                }
                            }
                        });
                    })
                }
            })
            // 生成关键词云
            generate_paperKeywords(state.paperId).then((response) => {
                if(response.data.status.code === 0){
                    // state.urlPK = "@/assets/paperKeywords.png";
                    state.loadingPK = false;
                }
            })
            checkLaTex()
        });

        // ----------------定义的function，由下至上编写---------------
        const handleAuthor = (author_id) => {
            window.open('/author_show_demo?author_id=' + author_id, '_blank')
        }

        const onSearch = () => {
            router.push('/ordinarySearch_demo?searchField='+state.searchField+'&searchQuery='+state.searchQuery+'&tagsChecked='+JSON.stringify(state.tagsChecked.slice()))
        }

        const onPageCiteChange = pageNumber => {
            state.currentPageCite = pageNumber;
        }

        const mock_onPageChange = pageNumber => {
            state.mock_currentPage = pageNumber;
        }


        const onPageRefChange = pageNumber => {
            state.currentPageRef = pageNumber;
        }

        const handleFavorite = (paper_id) => {
            favorite(paper_id).then(() => {
                // 请求成功后，前端处理数据
                state.data.forEach((paper) => {
                    if (paper.paper_id === paper_id) {
                        paper.favorite = !paper.favorite;
                    }
                });
            });
        }

        const handleRead = (paper_id) => {
            // 记录用户浏览论文历史
            browsing(paper_id).then((response) => {
                if(response.data.status.code === 0){
                    console.log("浏览埋点设置成功")
                }
            })
            window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
        }

        const handlePDF = (url) => {
            // 使用split方法按照'/'分割字符串，取得最后一个元素
            const parts = url.split("/");
            // 取得最后一个元素，即'0707.3421'
            const paper_id = parts[parts.length - 1];
            window.open('https://arxiv.org/pdf/' + paper_id + '.pdf', '_blank')
        }

        const registerDisabled = computed(() => {
            return !(registerForm.username && registerForm.password && registerForm.identity);
        });

        const validateUsername = (rule, value) => {
            return new Promise((resolve, reject) => {
                if (value.length === 0) {
                    resolve()
                }
                validate_username(value).then((response) => {
                    const { code, message } = response.data.status
                    if (code === 0) {
                        resolve()
                    } else {
                        reject(message)
                    }
                })
            })
        }

        const onRegisterFinish = values => {
            register(values.email, values.username, values.password, values.identity).then((response) => {
                if (response.data.status.code === 0) {
                    //注册成功
                    store.commit('CLEAR_USER_INFO')
                    store.commit('SET_TOKEN', response.data.data)
                    notification['success']({
                        message: '成功',
                        description: '注册成功',
                    })
                    state.loginShow = true;
                    state.registerShow = false;
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })
        }

        const onRegisterShow = () => {
            state.loginShow = false;
            state.registerShow = true;
        };

        const onLoginFinish = values => {
            login(values.username, values.password, values.remember).then((response) => {
                store.commit('CLEAR_USER_INFO')
                store.commit('CLEAR_TOKEN')
                if (response.data.status.code === 0) {
                    state.loginShow = false;
                    state.login = true;

                    store.commit('SET_LOGOUT', false)
                    //成功后继续请求用户信息
                    store.commit('SET_TOKEN', response.data.data)
                    console.log(response.data.data)
                    user_info()
                            .then((response) => {
                                if (response.data.status.code === 0) {
                                    // 成功后设置用户信息
                                    store.commit('SET_USER_INFO', response.data.data.user)
                                    console.log(response.data.data.user)
                                    // if ($route.redirectedFrom) {
                                    //     router.push({
                                    //         path: decodeURIComponent($route.redirectedFrom.fullPath),
                                    //     })
                                    // } else {
                                    //     router.push('/')
                                    // }
                                } else {
                                    notification['error']({
                                        message: '错误',
                                        description: response.data.status.message,
                                    })
                                }
                            })
                            .catch()
                } else if (response.data.status.code === 1 || response.data.status.code === 2) {
                    notification['warning']({
                        message: '登录失败',
                        description: '您提供的用户名或密码无效',
                    })
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })

        };

        const onLoginShow = () => {
            state.loginShow = true;
        };

        const logout = () => {
            state.login = false;
            logout_request()
                    .then((response) => {
                        if (response.data) {
                            //退出成功
                            store.commit('SET_LOGOUT', true)
                            store.commit('CLEAR_USER_INFO')
                            store.commit('CLEAR_TOKEN')
                            // 清空本地存储的数据
                            sessionStorage.clear()
                            // 其他操作...
                        }
                    })
                    .catch(() => {
                        store.commit('SET_LOGOUT', true)
                        store.commit('CLEAR_USER_INFO')
                        store.commit('CLEAR_TOKEN')
                    })
        }

        const onMenuClick = ({ key }) => {
            switch (key) {
                case 'center': {
                    window.open('/user_center_demo', '_blank')
                    break
                }
                case 'favorite': {
                    window.open('/user_center_demo?currentKey=3&&selectedKeys=3&&openKeys=2', '_blank')
                    break
                }
                case 'interest': {
                    window.open('/user_center_demo?currentKey=4&&selectedKeys=4&&openKeys=2', '_blank')
                    break
                }
                case 'logout': {
                    logout()
                }
            }
        }

        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        // --------------------定义的vue变量------------------------
        // 确保在使用 '$route' 之前已经声明并初始化了它
        const router = useRouter()
        const $route = useRoute();
        const store = useStore()

        // --------------------定义的响应数据-----------------------
        const chart = ref();

        const state = reactive({
            mock_List: [],
            mock_Total: 0,
            mock_currentPage: 1,
            loadingPK: true,
            // urlPK: '',
            activeKey: '1',
            citeTotal: 0,
            refTotal: 0,
            currentPageCite: 1,
            currentPageRef: 1,
            citeList: [],
            refList: [],
            ellipsis: true,
            data: null,
            paperId: -1,
            formRef: null,
            registerShow: false,
            loginShow: false,
            login: true,
            searchOptions: [
                { label: '标题', value: 'title' },
                { label: '摘要', value: 'abstract' },
                { label: '作者', value: 'author' },
                { label: '期刊', value: 'journal' },
            ],
            searchQuery: '',
            searchField: 'title',
            backGroundImg: require('@/assets/background2.png'),
            systemTitle: process.env.VUE_APP_TITLE,
        })

        const paginatedCiteList = computed(() => {
            const startIndex = (state.currentPageCite - 1) * 10;
            const endIndex = startIndex + 10;
            return state.citeList.slice(startIndex, endIndex);
        });

        const mock_paginatedList = computed(() => {
            const startIndex = (state.mock_currentPage - 1) * 10;
            const endIndex = startIndex + 10;
            return state.mock_List.slice(startIndex, endIndex);
        });

        // 由于后端需要调用API，为防止响应次数过多导致数据获取失败，在后端一次获取全部数据，并赋予state.list，然后在前端使用计算变量来改变需要显示的数据
        const paginatedRefList = computed(() => {
            const startIndex = (state.currentPageRef - 1) * 10;
            const endIndex = startIndex + 10;
            return state.refList.slice(startIndex, endIndex);
        });

        const registerForm = reactive({
            username: '',
            password: '',
            identity: null,
            email: '',
        });

        const loginForm = reactive({
            username: '',
            password: '',
            remember: false,
        });

        // ----------------------定义的常量--------------------
        const graph = {
            "nodes": [],
            "links": [],
            "categories": [
                { name: '参考文献' },
                { name: '引证文献' },
                { name: '中心论文' },
            ]
        }

        const identityOptions = [{
            label: '学生',
            value: '1',
        }, {
            label: '教授',
            value: '2',
        }, {
            label: '副教授',
            value: '3',
        }, {
            label: '讲师',
            value: '4',
        }]

        // ----------------------return函数-------------------
        return {
            handleAuthor,
            mock_onPageChange,
            mock_paginatedList,
            chart,
            paginatedCiteList,
            paginatedRefList,
            onSearch,
            onPageCiteChange,
            onPageRefChange,
            handleFavorite,
            handleRead,
            handlePDF,
            registerDisabled,
            validateUsername,
            identityOptions,
            onRegisterFinish,
            onRegisterShow,
            onLoginFinish,
            onLoginShow,
            onMenuClick,
            ...toRefs(state),
            registerForm,
            loginForm,
        }

    },
})
</script>

<style scoped>
.active {
    background-color: #4F4F4F;
    color: white;
}
.inactive {
    background-color: white;
    color: #4F4F4F;
}

.tab-header{
    width: 150px;
    height: 50px;
    background-color: #666666;
    color: white;
    text-align: center; /* 文本水平居中 */
    line-height: 50px; /* 设置和div高度相同的值，使文本垂直居中 */;
    display: flex; /* 垂直居中时可以使用flexbox */
    justify-content: center; /* 文本垂直居中 */
    align-items: center; /* 文本垂直居中 */
    font-size: 20px; /* 设置字体大小 */
}

/*分割线*/
.custom-divider {
    border: none;
    height: 1px;
    background-color: #BBBBBB;
}
</style>